package com.example.chengzhengwei;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "settings.db";
    private static final int DATABASE_VERSION = 2; // 升级数据库版本
    private static final String TABLE_SETTINGS = "parameters"; // 原有表名
    private static final String TABLE_RUN_DATA = "run_data"; // 新增数据表

    // 原有表结构字段
    private static final String COLUMN_ID = "id";
    public static final String COLUMN_TEMPERATURE = "temperature";
    public static final String COLUMN_TIME_MINUTES = "time_minutes";
    public static final String COLUMN_TIME_SECONDS = "time_seconds";
    public static final String COLUMN_FLUORESCENCE_PERIOD = "fluorescence_period";

    // 新增表结构字段
    public static final String COLUMN_CHANNEL = "channel";
    public static final String COLUMN_VALUE = "value";
    public static final String COLUMN_TIMESTAMP = "timestamp";
    public static final String COLUMN_DATA_TEMPERATURE = "data_temperature"; // 新增温度字段
    public static final String COLUMN_GENERATION_COUNT = "generation_count"; // 新增生成次数字段

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建原有设置表
        String createSettingsTable = "CREATE TABLE " + TABLE_SETTINGS + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                COLUMN_TEMPERATURE + " REAL NOT NULL," +
                COLUMN_TIME_MINUTES + " INTEGER NOT NULL," +
                COLUMN_TIME_SECONDS + " INTEGER NOT NULL," +
                COLUMN_FLUORESCENCE_PERIOD + " INTEGER NOT NULL" +
                ")";
        db.execSQL(createSettingsTable);

        // 创建新的数据记录表
        String createDataTable = "CREATE TABLE " + TABLE_RUN_DATA + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                COLUMN_CHANNEL + " INTEGER NOT NULL," +
                COLUMN_VALUE + " REAL NOT NULL," +
                COLUMN_TIMESTAMP + " LONG NOT NULL," +
                COLUMN_TIME_MINUTES + " INTEGER NOT NULL," +
                COLUMN_TIME_SECONDS + " INTEGER NOT NULL," +
                COLUMN_DATA_TEMPERATURE + " REAL NOT NULL," + // 新增温度字段
                COLUMN_GENERATION_COUNT + " INTEGER NOT NULL" + // 新增生成次数字段
                ")";
        db.execSQL(createDataTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
            // 只创建新表，保留原有表数据
            String createDataTable = "CREATE TABLE " + TABLE_RUN_DATA + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                    COLUMN_CHANNEL + " INTEGER NOT NULL," +
                    COLUMN_VALUE + " REAL NOT NULL," +
                    COLUMN_TIMESTAMP + " LONG NOT NULL," +
                    COLUMN_TIME_MINUTES + " INTEGER NOT NULL," +
                    COLUMN_TIME_SECONDS + " INTEGER NOT NULL," +
                    COLUMN_DATA_TEMPERATURE + " REAL NOT NULL," + // 新增温度字段
                    COLUMN_GENERATION_COUNT + " INTEGER NOT NULL" + // 新增生成次数字段
                    ")";
            db.execSQL(createDataTable);
        }
    }

    // 原有设置数据操作方法
    public void insertData(double temperature, int timeMinutes, int timeSeconds, int fluorescencePeriod) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete(TABLE_SETTINGS, null, null);
            ContentValues values = new ContentValues();
            values.put(COLUMN_TEMPERATURE, temperature);
            values.put(COLUMN_TIME_MINUTES, timeMinutes);
            values.put(COLUMN_TIME_SECONDS, timeSeconds);
            values.put(COLUMN_FLUORESCENCE_PERIOD, fluorescencePeriod);
            db.insert(TABLE_SETTINGS, null, values);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public Cursor getAllData() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(TABLE_SETTINGS, null, null, null, null, null, null);
    }

    // 新增数据操作方法
    public void saveRunData(int channel, float value, long timestamp, int minutes, int seconds, float temperature, int generationCount) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_CHANNEL, channel);
        values.put(COLUMN_VALUE, value);
        values.put(COLUMN_TIMESTAMP, timestamp);
        values.put(COLUMN_TIME_MINUTES, minutes);
        values.put(COLUMN_TIME_SECONDS, seconds);
        values.put(COLUMN_DATA_TEMPERATURE, temperature); // 新增温度字段
        values.put(COLUMN_GENERATION_COUNT, generationCount); // 新增生成次数字段

        db.insert(TABLE_RUN_DATA, null, values);
        db.close();
    }

    public void clearRunData() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_RUN_DATA);
        db.close();
    }

    public List<RunData> getRunData() {
        List<RunData> dataList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        String query = "SELECT * FROM " + TABLE_RUN_DATA + " ORDER BY " + COLUMN_TIMESTAMP;
        Cursor cursor = db.rawQuery(query, null);

        // 获取列索引
        int idIndex = cursor.getColumnIndex(COLUMN_ID);
        int channelIndex = cursor.getColumnIndex(COLUMN_CHANNEL);
        int valueIndex = cursor.getColumnIndex(COLUMN_VALUE);
        int timestampIndex = cursor.getColumnIndex(COLUMN_TIMESTAMP);
        int minutesIndex = cursor.getColumnIndex(COLUMN_TIME_MINUTES);
        int secondsIndex = cursor.getColumnIndex(COLUMN_TIME_SECONDS);
        int temperatureIndex = cursor.getColumnIndex(COLUMN_DATA_TEMPERATURE); // 新增温度字段
        int generationCountIndex = cursor.getColumnIndex(COLUMN_GENERATION_COUNT); // 新增生成次数字段

        if (cursor.moveToFirst()) {
            do {
                // 安全地获取列值
                int id = cursor.getInt(idIndex);
                int channel = cursor.getInt(channelIndex);
                float value = cursor.getFloat(valueIndex);
                long timestamp = cursor.getLong(timestampIndex);
                int minutes = cursor.getInt(minutesIndex);
                int seconds = cursor.getInt(secondsIndex);
                float temperature = cursor.getFloat(temperatureIndex); // 新增温度字段
                int generationCount = cursor.getInt(generationCountIndex); // 新增生成次数字段

                dataList.add(new RunData(id, channel, value, timestamp, minutes, seconds, temperature, generationCount));
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return dataList;
    }

    public void saveParameters(double temperature, int minutes, int seconds, int fluorescencePeriod) {
        SQLiteDatabase db = this.getWritableDatabase();

        // 先删除旧数据
        db.delete(TABLE_SETTINGS, null, null);

        // 插入新数据
        ContentValues values = new ContentValues();
        values.put(COLUMN_TEMPERATURE, temperature);
        values.put(COLUMN_TIME_MINUTES, minutes);
        values.put(COLUMN_TIME_SECONDS, seconds);
        values.put(COLUMN_FLUORESCENCE_PERIOD, fluorescencePeriod);

        db.insert(TABLE_SETTINGS, null, values);
        db.close();
    }
}

// 数据模型类
class RunData implements Serializable {
    private int id;
    private int channel;
    private float value;
    private long timestamp;
    private int minutes;
    private int seconds;
    private float temperature; // 新增温度字段
    private int generationCount; // 新增生成次数字段

    public RunData(int id, int channel, float value, long timestamp, int minutes, int seconds, float temperature, int generationCount) {
        this.id = id;
        this.channel = channel;
        this.value = value;
        this.timestamp = timestamp;
        this.minutes = minutes;
        this.seconds = seconds;
        this.temperature = temperature; // 新增温度字段
        this.generationCount = generationCount; // 新增生成次数字段
    }

    // Getter方法
    public int getId() { return id; }
    public int getChannel() { return channel; }
    public float getValue() { return value; }
    public long getTimestamp() { return timestamp; }
    public int getMinutes() { return minutes; }
    public int getSeconds() { return seconds; }
    public float getTemperature() { return temperature; } // 新增温度字段
    public int getGenerationCount() { return generationCount; } // 新增生成次数字段
}